package com.sunsharing.transport.mina;

import com.sunsharing.common.Constant;
import com.sunsharing.common.Context;
import com.sunsharing.common.URL;
import com.sunsharing.transport.Channel;
import com.sunsharing.transport.LongChannel;
import org.apache.log4j.Logger;
import org.apache.mina.core.session.IoSession;

/**
 * Created with IntelliJ IDEA.
 * User: criss
 * Date: 13-3-31
 * Time: 下午9:54
 * To change this template use File | Settings | File Templates.
 */
public class MinaChannel extends LongChannel {
    Logger logger = Logger.getLogger(MinaChannel.class);

    IoSession session;
    public MinaChannel(IoSession s,URL url)
    {
        super(url);
        this.session = s;
    }
    @Override
    protected void sendMsg(Context context)
    {
        logger.info("送回报文:"+context.getMsg().msg);

        if(session!=null)
        {
            session.write(context);
            //super.sendMsg(context);
        }
    }

    public void stop()
    {
        super.stop();
        if(session!=null)
        {
            try
            {
                session.close(true);
            }catch (Exception e)
            {

            }
        }
        session = null;
    }

    public boolean isclose()
    {
        if(this.session ==null)
        {
            return true;
        } else
        {
            return false;
        }
    }

    public void clone(Channel s)
    {
        this.session = ((MinaChannel)s).session;
        this.setUrl(s.url);
    }

    public void reconnect()
    {
       if(this.isClient())
       {
           this.stop();
           try
           {
            new MinaClient().connect(url,this.getIoHandle());
           }catch (Exception e)
           {
               logger.error("连接错误",e);
           }
       }
    }

}
